package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.Product;
import service.ProductService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class GetBooksServlet extends HttpServlet {
    //
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       JSONObject paramsObject=GetRequestJsonUtils.getRequestJsonObject(req);
       if (paramsObject!=null) {
           if (paramsObject.containsKey("category")) {
               String category = paramsObject.getString("category");
           }
           if (paramsObject.containsKey("pageSize")) {
               int pageSize = paramsObject.getInteger("pageSize");
           }
           if (paramsObject.containsKey("pageIndex")) {
               int pageIndex = paramsObject.getInteger("pageIndex");
           }
       }
        ProductService service=new  ProductService();
        Response build=null;
        if (paramsObject==null){
           try {
              List<Product> books = service.getAllProducts();
              build=Response.build(ResponseCode.SUCCESS,books);
           }catch (SQLException e){
                e.printStackTrace();
                build=Response.build(ResponseCode.ERROR_DB);
           }
       }else {
            build=Response.build(ResponseCode.ERROR);
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
